//
//  AudioManager.swift
//  Demo3
//
//  Created by Bigboss on 2025/3/10.
//

// AudioManager.swift
import AVFoundation

class AudioManager: ObservableObject {
    static let shared = AudioManager()
    private var players: [String: AVAudioPlayer] = [:]
    
    enum SoundType: String {
        case sceneTransition = "transition_whoosh"
        case buttonClick = "click_soft"
        case warningAlert = "alert_high"
    }
    
    // 预加载所有音效
    private init() {
        preloadSounds()
    }
    
    private func preloadSounds() {
        load(sound: .sceneTransition)
        load(sound: .buttonClick)
        load(sound: .warningAlert)
    }
    
    private func load(sound: SoundType) {
        guard let url = Bundle.main.url(forResource: sound.rawValue, withExtension: "caf") else {
            print("⚠️ 音频文件加载失败: \(sound.rawValue)")
            return
        }
        
        do {
            let player = try AVAudioPlayer(contentsOf: url)
            player.prepareToPlay()
            players[sound.rawValue] = player
        } catch {
            print("🔇 音频初始化失败: \(error.localizedDescription)")
        }
    }
    
    func play(_ sound: SoundType, volume: Float = 1.0) {
        guard let player = players[sound.rawValue] else { return }
        
        DispatchQueue.main.async {
            player.volume = volume
            player.currentTime = 0 // 重置播放位置
            player.play()
        }
    }
}
